import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 27
 * Time: 16:27
 */
//牛客 求二叉树的层序遍历
class TreeNode {
   int val = 0;
   TreeNode left = null;
   TreeNode right = null;
   public TreeNode(int val) {
       this.val = val;
    }
  }
public class Solution1 {
    //法一 官方推荐方法非递归
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();//也可以用链表实现队列
        ArrayList<ArrayList<Integer>> arrayLists1 = new ArrayList<>();
        if(root == null) return arrayLists1;//如果root==null则要这样返回
        queue.offer(root);
        while (!queue.isEmpty()) {
            ArrayList<Integer> arrayList2 = new ArrayList<>();
            int size = queue.size();
            while(size > 0) {
                TreeNode node = queue.poll();
                if(node.left != null) {//这个条件很重要
                    queue.offer(node.left);
                }
                if(node.right != null) {//这个条件很重要
                    queue.offer(node.right);
                }
                arrayList2.add(node.val);
                size--;
            }
            arrayLists1.add(arrayList2);
        }
        return arrayLists1;
    }

    //法二 官方方法递归
    ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> levelOrder1 (TreeNode root) {
        if (root == null) return arrayList;
        traverse(root, 1);
        return arrayList;
    }
    public void traverse(TreeNode root, int depth) {
        if (root == null) return;
        if(arrayList.size() < depth) {
            ArrayList<Integer> row = new ArrayList<>();
            row.add(root.val);
            arrayList.add(row);
        }else {
            arrayList.get(depth - 1).add(root.val);
        }
        traverse(root.left, depth + 1);
        traverse(root.right, depth + 1);
    }
}
